package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.utils.UserThreadLocal;

import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.SexEnum;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyCenterService {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private IMService imService;

    @DubboReference(version = "1.0.0")
    private UserApi userApi;

    @Autowired
    private TanHuaService tanHuaService;

    @DubboReference(version = "1.0.0")
    private SettingsApi settingsApi;

    @DubboReference(version = "1.0.0")
    private QuestionApi questionApi;

    @DubboReference(version = "1.0.0")
    private BlackListApi blackListApi;


    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (null == userId) {
            userId = UserThreadLocal.get();
        }

        //根据用户id查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);

        //封装UserInfoVo
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 是否喜欢
     *
     * @param userId
     * @return
     */
    public Boolean isLike(Long userId) {
        return this.userLikeApi.isLike(UserThreadLocal.get(), userId);
    }

    /**
     * 更新用户信息
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {

        userInfoVo.setId(UserThreadLocal.get());
        UserInfo userInfo = BeanUtil.toBeanIgnoreError(userInfoVo, UserInfo.class);
        userInfo.setSex(ObjectUtil.equals("man", userInfoVo.getGender()) ? SexEnum.MAN : SexEnum.WOMAN);
        Boolean result = this.userInfoApi.update(userInfo);
        if (result) {
            return true;
        }
        return false;
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public Object queryCounts() {
        Long userId = UserThreadLocal.get();
        //喜欢数
        Long likeCount = this.userLikeApi.queryLikeCount(userId);
        //粉丝数
        Long fanCount = this.userLikeApi.queryFanCount(userId);
        //相互喜欢数
        Long eachLoveCount = this.userLikeApi.queryMutualLikeCount(userId);

        CountsVo countsVo = new CountsVo();
        countsVo.setFanCount(fanCount);
        countsVo.setLoveCount(likeCount);
        countsVo.setEachLoveCount(eachLoveCount);

        return countsVo;
    }

    /**
     * 互相关注、我关注、粉丝、谁看过我 - 翻页列表
     *
     * @param type     1 互相关注 2 我关注 3 粉丝 4 谁看过我
     * @param page
     * @param pageSize
     * @param nickname
     * @return
     */
    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickname) {
        //创建返回对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        List<Object> userIdList;
        Long userId = UserThreadLocal.get();
        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type) {
            case 1: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 2: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 3: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 4: {
                PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "visitorUserId");
                break;
            }
            default:
                return pageResult;
        }

        if (CollUtil.isEmpty(userIdList)) {
            return pageResult;
        }

        //封装对象
        List<UserLikeListVo> userLikeList = new ArrayList<>();
        //根据用户id集合查询用户信息
        List<UserInfo> userInfoList ;

        if (ObjectUtil.isEmpty(nickname)) {
            userInfoList = this.userInfoApi.queryByUserIdList(userIdList);
        } else {
            userInfoList = this.userInfoApi.queryListLikeNickName(userIdList, nickname);
        }
        if (ObjectUtil.isEmpty(userInfoList)) {
            return pageResult;
        }
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = BeanUtil.toBeanIgnoreError(userInfo, UserLikeListVo.class);
            //性别
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setMarriage(ObjectUtil.equal(userInfo.getMarriage(), "已婚") ? 1 : 0);
            //是否喜欢  userLikeApi中的isLike开放出来
            userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId, userInfo.getUserId()));
            //缘分值
            Double result = this.recommendUserApi.queryScore(userInfo.getUserId(), userId);
            userLikeListVo.setMatchRate(Convert.toInt(result));

            userLikeList.add(userLikeListVo);
        }

        pageResult.setItems(userLikeList);


        return pageResult;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     */
    public void disLike(Long userId) {
        //判断当前用户与此用户是否相互喜欢
        Long myId = UserThreadLocal.get();
        Boolean mutualLike = this.userLikeApi.isMutualLike(myId, userId);

        //取消喜欢
        this.userLikeApi.notLikeUser(myId, userId);

        if (mutualLike) {
            //取消好友关系，解除在环信平台的好友关系
            this.imService.removeUser(userId);
        }
    }

    public void likeFan(Long userId) {
        //喜欢用户，如果用户是相互喜欢的话就会成为好友
        this.tanHuaService.likeUser(userId);
    }

    /**
     * 查询配置
     *
     * @return
     */
    public SettingsVo querySettings() {
        SettingsVo settingsVo = new SettingsVo();
        Long userId = UserThreadLocal.get();

        //设置用户的基本信息
        settingsVo.setId(userId);
        User user = this.userApi.queryById(userId);
        settingsVo.setPhone(user.getMobile());

        //查询用户的配置数据
        Settings settings = this.settingsApi.querySettings(userId);
        if (ObjectUtil.isNotEmpty(settings)) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }

        //查询陌生人问题
        settingsVo.setStrangerQuestion(this.tanHuaService.queryQuestion(userId));

        return settingsVo;
    }

    /**
     * 设置陌生人问题
     *
     * @param content
     */
    public void saveQuestions(String content) {
        Long userId = UserThreadLocal.get();
        this.questionApi.save(userId, content);
    }

    /**
     * 查询黑名单列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryBlacklist(Integer page, Integer pageSize) {

        Long userId = UserThreadLocal.get();

        IPage<BlackList> blackListIPage = this.blackListApi.queryBlacklist(userId, page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(Convert.toInt(blackListIPage.getTotal()));
        pageResult.setPages(Convert.toInt(blackListIPage.getPages()));

        List<BlackList> records = blackListIPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<Object> userIds = CollUtil.getFieldValues(records, "blackUserId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIds);

        List<BlackListVo> blackListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    //取消黑名单
    public void delBlacklist(Long userId) {
        Long myId = UserThreadLocal.get();
        this.blackListApi.delBlacklist(myId, userId);
    }

    //更新通知
    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        Long myId = UserThreadLocal.get();
        this.settingsApi.updateNotification(myId, likeNotification, pinglunNotification, gonggaoNotification);
    }


    public Boolean sendVerificationCode(String token) {
        //校验token
        Long userId = this.userService.checkToken(token);
        if (ObjectUtil.isEmpty(userId)) {
            return false;
        }
        User user = this.userApi.queryById(userId);
        Object result = this.smsService.sendCheckCode(user.getMobile());
        return null == result;
    }

    //校验验证码
    public Boolean checkVerificationCode(String code, String token) {
        //校验token
        Long userId = this.userService.checkToken(token);
        User user = this.userApi.queryById(userId);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }

        //校验验证码，先查询redis中的验证码
        String redisKey = "CHECK_CODE_" + user.getMobile();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StrUtil.equals(code, value)) {
            //将验证码删除
            this.redisTemplate.delete(redisKey);
            return true;
        }

        return false;
    }

    //保存新手机号
    public Boolean updatePhone(String token, String newPhone) {
        //校验token
        Long userId = this.userService.checkToken(token);
        User user = this.userApi.queryById(userId);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }
        return this.userService.updatePhone(user.getId(), newPhone);
        //if (result) {
        //    String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
        //    this.redisTemplate.delete(redisKey);
        //}

        //return result;
    }
}


